package org.zttc.itat.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.zttc.itat.dao.IUserDao;
import org.zttc.itat.exception.NewsException;
import org.zttc.itat.model.Pager;
import org.zttc.itat.model.User;

@Service("userService")
public class UserService implements IUserService {
	
	@Resource(name="userDao")
	private IUserDao userDao;

	@Override
	public void add(User user) {
		// TODO 如果存在部门要先验证部门是否存在，如果不存在就直接添加用户
		userDao.add(user);
	}

	@Override
	public void update(User user) {
		userDao.update(user);
	}

	@Override
	public void delete(int id) {
		//TODO 删除用户之前，先删除用户所关联的新闻信息
		userDao.delete(id);
	}

	@Override
	public User load(int id) {
		return userDao.load(id);
	}
	
	private User loadByUsername(String username) {
		String hql = "select u from User u where u.username=?";
		return (User)userDao.queryByHql(hql,username);
	}

	@Override
	public User login(String username, String password) {
		User u = this.loadByUsername(username);
		if(u==null) throw new NewsException("用户名不存在");
		if(!u.getPassword().equals(password)) throw new NewsException("用户密码不正确");
		return u;
	}

	@Override
	public Pager<User> findUser(String con) {
		Pager<User> users = null;
		if(con!=null){
			users = userDao.find("from User u where u.username like ? or u.nickname like ?",new Object[]{"%"+con+"%","%"+con+"%"});
		}else{
			users = userDao.find("from User");
		}
		return users;
	}

}
